package com.shebei.api.equipment_api_test.http;


import com.alibaba.fastjson.JSONObject;
import com.shebei.api.equipment_api_test.service.HeadParsing;
import com.shebei.api.equipment_api_test.utils.GetConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Base64;
import java.util.Map;

@Component
public class HttpClientGetImage implements HttpClienInterface {


    @Autowired
    HttpClientFormUrlencoded httpClientFormUrlencoded;
    @Override
    public String sendRequest(String url, String requestBody, Map<String, String> head) {
        Boolean isRightCode=false;
        String verifyCode=null;
        String msg="success";
        int i=0;
        int max=5;
        while (!isRightCode){
            String reg="^[a-zA-Z0-9]{4}$";
            verifyCode=sendGetRequset(url,requestBody,head);
            isRightCode=verifyCode.matches(reg);
            i++;
            if(i==max){
                isRightCode=true;
            }
        }
        if(i==max ){
            msg="failed";
        }

        JSONObject body= new JSONObject();

        body.put("verifyCode",verifyCode);
        body.put("msg",msg);
        return body.toJSONString();
    }

    private   String doGet(String url, Map<String, String> param,Map<String, String> head) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, String.valueOf(param.get(key)));
                }
            }
            URI uri = builder.build();
            System.out.println("请求URL为："+uri);
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            httpGet.addHeader("content-type", "application/json");
            httpGet.addHeader("Accept", "image/jpeg");
            httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
            if (head != null){
                for (String key : head.keySet()) {
                    httpGet.setHeader(key,String.valueOf(head.get(key)));
                }


            }

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                System.out.println(response.getEntity().getContentType());
                InputStream in=response.getEntity().getContent();
                BufferedImage res= ImageIO.read(in);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ImageIO.write(res, "png", stream);
                String s = Base64.getEncoder().encodeToString(stream.toByteArray());

                System.out.println("base64Str:"+s);
                resultString=s;
                //resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public String sendGetRequset(String url, String requestBody, Map<String, String> head) {


        Map param = JSONObject.parseObject(requestBody);

        String response=  doGet( url, param, head);

        if(response==null){
            return "获取验证码失败";
        }

        JSONObject body= new JSONObject();

        body.put("imageBase64",response);
        String ocrUrl=GetConfig.getAddress("orcSever");
        String ress= httpClientFormUrlencoded.sendRequest(ocrUrl,body.toJSONString(),null);
        System.out.println(ress);
        if(ress==null){
            return "OCR服务异常";
        }

        return ress;
    }
}

